package com.redwine.app.fragments;

import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.redwine.app.APP;
import com.redwine.app.MyCollectionActivity;
import com.redwine.app.R;
import com.redwine.app.adapter.MyCollectionAdapter;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.responses.MyCollectionProcurementResponse;
import com.redwine.app.net.responses.MyCollectionSupplyResponse;
import com.redwine.app.net.responses.SendMsgEvent;
import com.redwine.app.utils.Global;
import com.redwine.app.utils.NetUtil;
import com.redwine.app.view.EmptyView;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.redwine.app.utils.Utils.showToast;

/**
 * 我的收藏页面
 * 作者：gassion on 17/9/5 14:31
 * 最可怕的敌人，就是没有坚强的信念。
 */
public class MyCollectionFragment extends BaseFragment {

    public static final String PARAMS = "params";
    private boolean isPurchaseOrder = false;//是否是订货单
    private MyCollectionActivity findActivity;
    @ViewInject(R.id.common_no_title_refresh_list_view)
    PullToRefreshListView mListView;
    @ViewInject(R.id.empty_view)
    private EmptyView emptyView;
    private MyCollectionAdapter myCollectionAdapter;
    private int page = 1;//默认加载第一页
    private List<MyCollectionSupplyResponse.DataEntityX.DataEntity> dataEntityList = null;
    private List<MyCollectionProcurementResponse.DataEntityX.DataEntity> responseDataData = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        findActivity = (MyCollectionActivity) getActivity();
        if (getArguments() != null) {
            isPurchaseOrder = getArguments().getBoolean(PARAMS);
        }
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.activity_common_no_title_refresh_list_view, null);
        ViewUtils.inject(this, root);
        initView();
        requestCollectionListData(true);
        return root;
    }

    /**
     * 初始化view
     */
    private void initView() {
        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                requestCollectionListData(false);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page += 1;
                requestCollectionListData(false);
            }
        });
        mListView.setOnActionMoveListener(new PullToRefreshBase.OnActionMove() {
            @Override
            public void onMove(boolean isMove) {
                setUpdateTime(mListView);
            }
        });
        myCollectionAdapter = new MyCollectionAdapter(getActivity());
        mListView.setAdapter(myCollectionAdapter);
        mListView.setEmptyView(emptyView);
        emptyView.bind();
    }

    /**
     * 获取列表
     */
    private void requestCollectionListData(boolean isLoading) {
        if (!NetUtil.checkNet(getActivity())) {
            showToast(R.string.generic_check);
            if (!isPurchaseOrder) {
                if (null == dataEntityList) {
                    setErrorView(emptyView, mListView);
                }
            } else {
                if (null == responseDataData) {
                    setErrorView(emptyView, mListView);
                }
            }


            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (null != mListView)
                        mListView.onRefreshComplete();

                }
            }, 500);
            return;
        }

        String url = NetworkConstants.COLLECTION_LIST_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("size", "20");
        params.put("page", String.valueOf(page));
        params.put("uid", Global.user.getUid());
        params.put("type", isPurchaseOrder ? "2" : "1");
        if (!isPurchaseOrder) {
            if (isLoading)
                showWaiting();
            GsonRequest<MyCollectionSupplyResponse> request = new GsonRequest<>(url, Request.Method.POST,
                    MyCollectionSupplyResponse.class, false, params, new Response.Listener<MyCollectionSupplyResponse>() {
                @Override
                public void onResponse(MyCollectionSupplyResponse response) {
                    dismissWaiting();
                    if (null != mListView)
                        mListView.onRefreshComplete();
                    if (response.isSuccess()) {
                        MyCollectionSupplyResponse.DataEntityX responseData = response.getData();
                        if (null != responseData && null != responseData.getData() && !responseData.getData().isEmpty()) {
                            dataEntityList = responseData.getData();
                            myCollectionAdapter.setData(page, dataEntityList);
                            if (responseData.getPage() != responseData.getAllpage()) {
                                mListView.setMode(PullToRefreshBase.Mode.BOTH);
                            } else {
                                mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            }
                        } else {
                            myCollectionAdapter.setData(page, null);
                            setEmptyView(emptyView, mListView);
                        }
                    } else {
                        showToast(response.getMsg());
                        setEmptyView(emptyView, mListView);
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    dismissWaiting();
                    if (null != mListView)
                        mListView.onRefreshComplete();
                    showToast(R.string.generic_check);
                    setErrorView(emptyView, mListView);
                }
            });
            APP.getInstance().getRequestQueue().add(request);
        } else {
            if (isLoading)
                showWaiting();
            GsonRequest<MyCollectionProcurementResponse> request = new GsonRequest<>(url, Request.Method.POST,
                    MyCollectionProcurementResponse.class, false, params, new Response.Listener<MyCollectionProcurementResponse>() {
                @Override
                public void onResponse(MyCollectionProcurementResponse response) {
                    dismissWaiting();
                    if (null != mListView)
                        mListView.onRefreshComplete();
                    if (response.isSuccess()) {
                        MyCollectionProcurementResponse.DataEntityX responseData = response.getData();
                        if (null != responseData && null != responseData.getData() && !responseData.getData().isEmpty()) {
                            responseDataData = responseData.getData();
                            myCollectionAdapter.setProcurementData(page, responseDataData);
                            if (responseData.getPage() != responseData.getAllpage()) {
                                mListView.setMode(PullToRefreshBase.Mode.BOTH);
                            } else {
                                mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            }
                        } else {
                            myCollectionAdapter.setProcurementData(page, null);
                            setEmptyView(emptyView, mListView);
                        }
                    } else {
                        setEmptyView(emptyView, mListView);
                        showToast(response.getMsg());
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    dismissWaiting();
                    if (null != mListView)
                        mListView.onRefreshComplete();
                    showToast(R.string.generic_check);
                    setErrorView(emptyView, mListView);
                }
            });
            APP.getInstance().getRequestQueue().add(request);
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(SendMsgEvent event) {
        if (event.getSendType() == SendMsgEvent.REFURBISH_MY_COLLECTION) {
            requestCollectionListData(true);
        }
    }

    @Override
    protected void emptyOnclick() {
        emptyView.bind();
        if (null != mListView) {
            mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    mListView.setRefreshing();
                }
            }, 500);
        } else {
            requestCollectionListData(true);
        }
    }
}
